<template>
  <div class="page-wapper">
    <!-- 已发送日报管理 -->
    <div class="container">
      <!-- 顶部搜索栏 -->
      <div class="search_bar">
        <div class="left_search">
          <div class="filter_item">
            <div class="label">发送时间：</div>
            <!-- :default-time="['00:00:00', '23:59:59']" -->
            <el-date-picker
              v-model="filterData.reportTimeList"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              size="small"
            >
            </el-date-picker>
          </div>
        </div>
        <div class="right_search">
          <el-button-group>
            <el-button
              size="mini"
              :loading="searchBtnLoading"
              type="primary"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button size="mini" @click="handleReset"> 重置 </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="table_box f_1">
        <vxe-table
          v-loading="tableLoading"
          :data="tableData"
          :sort-config="{ remote: true }"
          ref="xTable"
          resizable
          align="center"
          border
          height="100%"
          show-overflow="tooltip"
          highlight-hover-row
          highlight-current-row
          class="xTable"
          @toggle-row-expand="toggleExpandChangeEvent"
        >
          <vxe-column
            type="seq"
            title="序号"
            width="60"
            fixed="left"
          ></vxe-column>

          <vxe-column type="expand" width="80" fixed="left">
            <template #content="{ row, rowIndex }">
              <div class="expand_wrapper">
                <ReportCommitList
                  ref="reportCommitListRef"
                  :lastFinishReportList="row.lastFinishReportList"
                  :todayPlanReportList="row.todayPlanReportList"
                  :reportCommitRemark="row.reportCommitRemark"
                />
              </div>
            </template>
          </vxe-column>

          <vxe-column
            field="createdTime"
            title="发送时间"
            width="160"
          ></vxe-column>

          <vxe-column
            field="reportCommitRemark"
            title="备注"
            align="left"
            header-align="center"
          ></vxe-column>

          <vxe-column #default="{ row }" width="100" title="操作" fixed="right">
            <div>
              <el-button size="mini" type="text" @click.stop="copyData(row)">
                复制
              </el-button>
              <el-button
                v-if="currentDateTime === row.dateStr"
                size="mini"
                type="text"
                style="color: #f78989"
                @click.stop="deleteTableDataMethod(row)"
              >
                撤回
              </el-button>
            </div>
          </vxe-column>
        </vxe-table>
      </div>
      <el-pagination
        v-model="pagenationData.current"
        :page-sizes="[500, 100, 50, 15]"
        :page-size="pagenationData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagenationData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
        style="text-align: center; margin-top: 10px"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  ref,
  reactive,
  nextTick,
  getCurrentInstance,
  onActivated,
  toRefs,
  computed,
} from "vue";
import { useStore } from "vuex";
import { ElMessage, ElMessageBox } from "element-plus";
import ReportCommitList from "./components/ReportCommitList.vue";

const initFilterData = () => {
  return {
    reportTimeList: [],
    startDateTime: null,
    endDateTime: null,
  };
};

export default {
  name: "SendedReportManage",
  components: { ReportCommitList },
  setup() {
    const { proxy } = getCurrentInstance();
    const $moment = proxy.$moment;
    const $api = proxy.$api;
    const store = useStore();

    // 当前的日期时间
    const currentDateTime = computed(() =>
      $moment(store.state.currentDateObj).format("YYYY-MM-DD")
    );

    // 搜索绑定的数据
    const filterData = reactive(initFilterData());
    // 真正的搜索条件
    const condition = reactive({});
    const searchBtnLoading = ref(false);

    // 预加载数据
    const prepareData = reactive({
      taskStatusSelectList: [],
      releaseIdSelectList: [],
      taskPrioritySelectList: [],
    });

    const tableState = reactive({
      columnsAll: {
        visible: true,
        title: "全选",
      },
      // 标签筛选列
      columns: [],
      // 列表标签筛选需要禁用筛选的选项
      disabledCancleColumns: ["序号", "操作"],
      xTable: null,
      tableData: [],
      tableLoading: false,
    });

    // 分页组件
    const pagenationData = reactive({
      current: 1,
      size: 15,
      total: 0,
    });

    // 重置
    const handleReset = () => {
      const initData = initFilterData();
      Object.keys(filterData).forEach((key) => {
        filterData[key] = initData[key];
      });
      pagenationData.current = 1;
      handleSearch();
    };

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      pagenationData.current = 1;
      getTableData();
    };

    // 获取列表数据
    const getTableData = () => {
      tableState.tableLoading = true;
      const params = {
        ...pagenationData,
        condition: {
          startCreatedTime: null,
          endCreatedTime: null,
        },
      };
      if (condition.reportTimeList && condition.reportTimeList.length) {
        params.condition.startCreatedTime = condition.reportTimeList[0];
        params.condition.endCreatedTime = condition.reportTimeList[1];
      }
      $api.reportCommit
        .listPageSelf(params)
        .then((res) => {
          tableState.tableLoading = false;
          tableState.tableData = res.data.list.map((item) => {
            return {
              ...item,
              dateStr: $moment(item.createdTime).format("YYYY-MM-DD"),
            };
          });
          pagenationData.total = res.data.total;
          pagenationData.current = res.data.current;
        })
        .catch((err) => {
          tableState.tableLoading = false;
          console.error("tableData error: ", err);
        });
    };

    // 删除单个内容
    const deleteTableDataMethod = (row) => {
      // 二次确认删除
      ElMessageBox.confirm(`确定要撤回今天的日报吗？`, "提示", {
        type: "warning",
      })
        .then(() => {
          deleteTableData([row.id]);
        })
        .catch(() => {});
    };

    // 删除全部
    const deleteAll = () => {
      if (!tableState.tableData.length) {
        return ElMessage.warning("没啥可删的");
      }
      const selectedList = tableState.tableData.filter((item) => item.checked);
      if (!selectedList.length) {
        return ElMessage.warning("请选择列表的数据");
      }
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除 ${selectedList.length} 条数据吗？`,
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          const ids = selectedList.map((item) => item.id);
          deleteTableData(ids);
        })
        .catch(() => {});
    };

    // 删除内容接口
    const deleteTableData = (ids) => {
      tableState.tableLoading = true;
      $api.reportCommit
        .removeByIds({
          ids,
        })
        .then((res) => {
          ElMessage.success("删除成功！");
          getTableData();
        })
        .catch((err) => {
          console.error("deleteReport error: ", err);
        })
        .finally(() => {
          tableState.tableLoading = false;
        });
    };

    // 查询已启用的所有角色列表
    // const getPreparedData = () => {
    //   $api.role
    //     .getEnableList()
    //     .then((res) => {
    //       prepareData.enableRoleSelectList = res.data || [];
    //     })
    //     .catch((err) => {
    //       console.error("getEnableList error: ", err);
    //     })
    //     .finally(() => {});
    // };

    // 筛选列-全选按钮
    const tagCheckedChange = (item) => {
      if (item.title === "全选") {
        // 点击全选操作
        tableState.columns.forEach((cell) => {
          cell.visible = item.visible;
          if (
            !item.visible &&
            tableState.disabledCancleColumns.includes(cell.title)
          ) {
            cell.visible = !item.visible;
          }
        });
      }
      tableState.columnsAll.visible = tableState.columns.every(
        (item) => item.visible
      );
      // 刷新布局
      tableState.xTable.refreshColumn();
    };

    // 动态设置单元行样式
    const rowStyle = ({ rowIndex }) => {
      if (tableState.tableData[rowIndex].checked) {
        return {
          backgroundColor: "pink",
        };
      }
    };

    // 分页-切换页大小
    const handleSizeChange = (size) => {
      pagenationData.size = size;
      getTableData();
    };

    // 分页-切换页数
    const handleCurrentChange = (current) => {
      pagenationData.current = current;
      getTableData();
    };

    const toggleExpandChangeEvent = () => {
      console.log("展开行事件");
    };

    const reportCommitListRef = ref(null);

    // 点击复制
    const copyData = (row) => {
      if (reportCommitListRef.value) {
        reportCommitListRef.value.copyData(row);
      } else {
        tableState.xTable && tableState.xTable.setRowExpand([row], true);
        nextTick(() => {
          reportCommitListRef.value.copyData(row);
        });
      }
    };

    // 初始化 -------------------------------------------
    // getPreparedData();

    // 获取所有列配置
    setTimeout(() => {
      nextTick(() => {
        tableState.columns = tableState.xTable.getColumns();
      });
    }, 100);

    onActivated(() => {
      handleSearch();
    });

    return {
      rowStyle,
      searchBtnLoading,
      handleSearch,
      handleReset,
      filterData,
      prepareData,
      deleteTableDataMethod,
      tagCheckedChange,
      getTableData,
      pagenationData,
      deleteAll,
      handleSizeChange,
      handleCurrentChange,
      toggleExpandChangeEvent,
      currentDateTime,
      copyData,
      reportCommitListRef,
      ...toRefs(tableState),
    };
  },
};
</script>

<style lang="less" scoped>
.message-title {
  cursor: pointer;
}
.handle-row {
  margin-top: 30px;
}

.expand_wrapper {
  padding: 10px;
  background: #f5f5f5;
  overflow: hidden;
}
</style>
